package com.groupbuying.provider.service.impl;

import com.groupbuying.provider.connector.AdminFeign;
import com.groupbuying.provider.connector.FileFegin;
import com.groupbuying.provider.connector.SysconfigFeign;
import com.groupbuying.provider.constants.CommonConstants;
import com.groupbuying.provider.constants.StoreOpexRuleRelPreSearchConstants;
import com.groupbuying.provider.context.FilterContextHandler;
import com.groupbuying.provider.dao.StoreMainInfoDao;
import com.groupbuying.provider.domain.*;
import com.groupbuying.provider.dto.*;
import com.groupbuying.provider.dto.convert.StoreShopDetailConvert;
import com.groupbuying.provider.dto.convert.WithdrawStoreConvert;
import com.groupbuying.provider.pojo.StoreMainInfoEnum;
import com.groupbuying.provider.service.*;
import com.groupbuying.provider.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class StoreMainInfoServiceImpl implements StoreMainInfoService {


    private static Logger log = LoggerFactory.getLogger(StoreMainInfoServiceImpl.class);

    @Autowired
    private StoreOpexRuleRelService storeOpexRuleRelService;
    @Autowired
    private StoreMainInfoDao storeMainInfoDao;
    @Autowired
    @Lazy
    private StoreCapitalVirtualAccountService storeCapitalVirtualAccountService;
    @Autowired
    @Lazy
    private StoreShopService storeShopService;
    @Autowired
    private StoreCompanyInfoService storeCompanyInfoService;
    @Autowired
    private CompanyQualificationService companyQualificationService;
    @Autowired
    private FileFegin fileFegin;
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private StoreCheckoutCounterService storeCheckoutCounterService;

    @Override
    public StoreMainInfoDO get(String uuid) {
        return storeMainInfoDao.get(uuid);
    }

    @Override
    public List<StoreMainInfoDO> list(Map<String, Object> map) {
        return storeMainInfoDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return storeMainInfoDao.count(map);
    }

    @Override
    public R storeShopDetail(Map<String, Object> params) {
        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return R.error("params is null");
        }
        StoreMainInfoDO storeMainInfoDO = storeMainInfoDao.get(storeUuid);
        StoreShopDO storeShopDO = storeShopService.getByStoreUuid(storeUuid);
        StoreCompanyInfoDO storeCompanyInfoDO = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeUuid);
        CompanyQualificationDO companyQualificationDO = companyQualificationService.getQualificationByCompanyUuid(storeCompanyInfoDO.getUuid());
        StoreCapitalVirtualAccountDO storeCapitalVirtualAccount = storeCapitalVirtualAccountService.getStoreCapitalVirtualAccountByStoreUuid(storeUuid);

        StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
        String withinphoto = storeShopDO.getWithinphoto();
        if (StringUtils.isNotBlank(withinphoto)) {
            storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(withinphoto));
        }
        String doorphoto = storeShopDO.getDoorphoto();
        if (StringUtils.isNotBlank(doorphoto)) {
            storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(doorphoto));
        }
        String legalidcard1 = storeCompanyInfoDO.getLegalidcard1();
        if (StringUtils.isNotBlank(legalidcard1)) {
            storePhotoDTO.setLegalidCard1(fileFegin.getDownloadUrlByFileGroupKey(legalidcard1));
        }
        String legalidcard2 = storeCompanyInfoDO.getLegalidcard2();
        if (StringUtils.isNotBlank(legalidcard2)) {
            storePhotoDTO.setLegalidCard2(fileFegin.getDownloadUrlByFileGroupKey(legalidcard2));
        }
        String settle1image = storeCompanyInfoDO.getSettle1image();
        if (StringUtils.isNotBlank(settle1image)) {
            storePhotoDTO.setSettle1Image(fileFegin.getDownloadUrlByFileGroupKey(settle1image));
        }
        String settle2image = storeCompanyInfoDO.getSettle2image();
        if (StringUtils.isNotBlank(settle2image)) {
            storePhotoDTO.setSettle2Image(fileFegin.getDownloadUrlByFileGroupKey(settle2image));
        }
        String bussinesslicensephoto = companyQualificationDO.getBussinesslicensephoto();
        if (StringUtils.isNotBlank(bussinesslicensephoto)) {
            storePhotoDTO.setBussinessLicensePhoto(fileFegin.getDownloadUrlByFileGroupKey(bussinesslicensephoto));
        }
        String agreementimage = storeCompanyInfoDO.getAgreementimage();
        if (StringUtils.isNotBlank(agreementimage)) {
            storePhotoDTO.setAgreementImage(fileFegin.getDownloadUrlByFileGroupKey(agreementimage));
        }
        String slideshow = storeShopDO.getSlideshow();
        if (StringUtils.isNotBlank(slideshow)) {
            storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(slideshow));
        }
        String authorizationletter = storeCompanyInfoDO.getAuthorizationletter();
        if (StringUtils.isNotBlank(authorizationletter)) {
            storePhotoDTO.setAuthorizationLetter(fileFegin.getDownloadUrlByFileGroupKey(authorizationletter));
        }
        String licenseimage = storeCompanyInfoDO.getLicenseimage();
        if (StringUtils.isNotBlank(licenseimage)) {
            storePhotoDTO.setLicenseimage(fileFegin.getDownloadUrlByFileGroupKey(licenseimage));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("storeMainInfo", storeMainInfoDO);
        result.put("storeShop", storeShopDO);
        result.put("storeCompanyInfo", storeCompanyInfoDO);
        result.put("companyQualification", companyQualificationDO);
        result.put("storeCapitalVirtualAccount", storeCapitalVirtualAccount);
        result.put("storePhotoDTO", storePhotoDTO);


        return R.ok(result);
    }

    @Override
    public R getListByPage(Map<String, Object> params) {

        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");


        Query query = new Query(params);
        List<StoreShopAuditPageDTO> smi = storeMainInfoDao.getListByPage(query);
        Map<String, Object> feignParam = new HashMap<>();
        for (StoreShopAuditPageDTO storeShopAuditPage : smi) {
            feignParam.clear();
            feignParam.put("agentId", storeShopAuditPage.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = JSONUtils.jsonToMap(jsonResult);
            String province = feignResult.get("province") != null ? feignResult.get("province").toString() : "";
            String city = feignResult.get("city") != null ? feignResult.get("city").toString() : "";
            String district = feignResult.get("district") != null ? feignResult.get("district").toString() : "";

            storeShopAuditPage.setAgentCity(String.format("%s  %s %s", province, city, district));
            storeShopAuditPage.setAgentName(feignResult.get("agentName").toString());
        }

        //int total = this.count(query);
        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreShopAuditPageDTO> totalList = storeMainInfoDao.getListByPage(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);
    }

    @Override
    public R getListByManagePage(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");

        Object temp = params.get("province");
        String provinceParam = temp != null ? temp.toString() : "";
        temp = params.get("city");
        String cityParam = temp != null ? temp.toString() : "";
        temp = params.get("district");
        String districtParam = temp != null ? temp.toString() : "";

        if (StringUtils.isNotBlank(provinceParam) || StringUtils.isNotBlank(cityParam) || StringUtils.isNotBlank(districtParam)) {
            List<Map> feignResultList = getAgentByArea(provinceParam, cityParam, districtParam);
            if (feignResultList != null && feignResultList.size() > 0) {
                params.put("agents", feignResultList);
            } else {
                //没有存在的地区值，直接返回
                return R.ok().put("page", new PageUtils(new ArrayList<StoreShopManagePageDTO>(), 0));
            }
        }

        Query query = new Query(params);
        List<StoreShopManagePageDTO> smi = storeMainInfoDao.getListByManagePage(query);

        Map<String, Object> feignParam = new HashMap<>();
        for (StoreShopManagePageDTO storeShopManagePage : smi) {
            feignParam.clear();
            feignParam.put("agentId", storeShopManagePage.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = null;
            if (StringUtils.isNotBlank(jsonResult)) {
                feignResult = JSONUtils.jsonToMap(jsonResult);
                String province = feignResult.get("province") != null ? feignResult.get("province").toString() : "";
                String district = feignResult.get("district") != null ? feignResult.get("district").toString() : "";
                String city = feignResult.get("city") != null ? feignResult.get("city").toString() : "";
                storeShopManagePage.setAgentCity(String.format("%s  %s %s", province, city, district));
                storeShopManagePage.setAgentName(feignResult.get("agentName").toString());

            }

        }

        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreShopManagePageDTO> totalList = storeMainInfoDao.getListByManagePage(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);

    }



    @Override
    public R getStoreOperList(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");
        Query query = new Query(params);
        List<StoreOperDTO> smi = storeMainInfoDao.getStoreOperList(query);
        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreOperDTO> totalList = storeMainInfoDao.getStoreOperList(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);
    }


    @Override
    public R getExportStoreMangeList(Map<String, Object> params) {

        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("auditStatus", StoreMainInfoEnum.BUSINESS_AUDIT_PASS);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");

        Object temp = params.get("province");
        String province = temp != null ? temp.toString() : "";
        temp = params.get("city");
        String city = temp != null ? temp.toString() : "";
        temp = params.get("district");
        String district = temp != null ? temp.toString() : "";

        if (StringUtils.isNotBlank(province) || StringUtils.isNotBlank(city) || StringUtils.isNotBlank(district)) {
            List<Map> feignResultList = getAgentByArea(province, city, district);
            if (feignResultList != null && feignResultList.size() > 0) {
                params.put("agents", feignResultList);
            } else {
                //没有存在的地区值，直接返回
                return R.ok().put("page", new PageUtils(new ArrayList<StoreManageExportPageDTO>(), 0));
            }

        }

        Query query = new Query(params);
        List<StoreManageExportPageDTO> storeManageExportPageDTOList = storeMainInfoDao.getExportStoreMangeList(query);
        Map<String, Object> feignParam = new HashMap<>();
        for (StoreManageExportPageDTO storeManageExportPageDTO : storeManageExportPageDTOList) {
            feignParam.clear();
            feignParam.put("agentId", storeManageExportPageDTO.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = null;
            if (StringUtils.isNotBlank(jsonResult)) {
                feignResult = JSONUtils.jsonToMap(jsonResult);
                storeManageExportPageDTO.setAgentName(feignResult.get("agentName").toString());
            }

            switch (storeManageExportPageDTO.getFreezeStatus()) {

                case StoreMainInfoEnum.FROZEN: {
                    storeManageExportPageDTO.setFreezeStatus("已冻结");
                }
                break;
                case StoreMainInfoEnum.UNFROZEN: {
                    storeManageExportPageDTO.setFreezeStatus("未冻结");
                }
                break;
            }

        }

        return R.ok().put("page", storeManageExportPageDTOList);
    }

    @Override
    public R getListByPageInFinance(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");


        Query query = new Query(params);
        List<StoreShopAuditPageDTO> smi = storeMainInfoDao.getListByPageInFinance(query);
        Map<String, Object> feignParam = new HashMap<>();
        for (StoreShopAuditPageDTO storeShopAuditPage : smi) {
            feignParam.clear();
            feignParam.put("agentId", storeShopAuditPage.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = JSONUtils.jsonToMap(jsonResult);
            String province = feignResult.get("province") != null ? feignResult.get("province").toString() : "";
            String city = feignResult.get("city") != null ? feignResult.get("city").toString() : "";
            String district = feignResult.get("district") != null ? feignResult.get("district").toString() : "";

            storeShopAuditPage.setAgentCity(String.format("%s  %s %s", province, city, district));
            storeShopAuditPage.setAgentName(feignResult.get("agentName").toString());
        }

        //int total = this.count(query);
        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreShopAuditPageDTO> totalList = storeMainInfoDao.getListByPage(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 通过地区获取代理商
     *
     * @param province
     * @param city
     * @param district
     * @return
     */
    private List<Map> getAgentByArea(String province, String city, String district) {
        Map areaParam = new HashMap();
        areaParam.put("province", province);
        areaParam.put("city", city);
        areaParam.put("district", district);
        String jsonResult = adminFeign.queryAgentByArea(areaParam);
        List<Map> feignResultList = null;
        if (StringUtils.isNotBlank(jsonResult)) {
            feignResultList = (List<Map>) JSONUtils.jsonToBean(jsonResult, new ArrayList());
            log.error("根据地区查询代理商结果：{}", jsonResult);
        }
        return feignResultList;
    }

    @Override
    public List<Map<String, String>> getUuidAndStoreName() {
        return storeMainInfoDao.getUuidAndStoreName();
    }

    @Override
    public R getShopDetail(Map<String, Object> params) {

        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return R.error("params is null");
        }
        StoreMainInfoDO storeMainInfoDO = storeMainInfoDao.get(storeUuid);
        StoreShopDO storeShopDO = storeShopService.getByStoreUuid(storeUuid);

        if (storeShopDO == null) {
            R.error();
        }

        Map queryCounterParam = new HashMap();
        queryCounterParam.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        queryCounterParam.put("storeuuid", storeUuid);
        List<StoreCheckoutCounterDO> checkoutCounterDOList = storeCheckoutCounterService.list(queryCounterParam);
        String counterId = checkoutCounterDOList != null && checkoutCounterDOList.size() > 0 ? checkoutCounterDOList.get(0).getUuid(): null;

        StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
        storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShopDO.getWithinphoto()));
        storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShopDO.getDoorphoto()));
        storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(storeShopDO.getSlideshow()));

        Map<String, Object> result = new HashMap<>();
        StoreShopTempDTO storeShopTempDTO = new StoreShopTempDTO();
        storeShopTempDTO.setStoreMainInfoDO(storeMainInfoDO);
        storeShopTempDTO.setStoreShopDO(storeShopDO);
        result.put("storePhotoDTO", storePhotoDTO);
        result.put("shopDetail", StoreShopDetailConvert.MAPPER.dTOToDTO(storeShopTempDTO));
        result.put("counterId",counterId);

        Map searchMap = new HashMap();
        searchMap.put(StoreOpexRuleRelPreSearchConstants.SEARCH_STOREID,storeUuid);
        searchMap.put(StoreOpexRuleRelPreSearchConstants.SEARCH_DELFLAG,CommonConstants.COMMON_FLAG_UNDEL);
        List <StoreOpexRuleRelDO> listOpex = storeOpexRuleRelService.list(searchMap);



        if (listOpex == null || listOpex.size() == 0) {
            return R.ok(result);
        }

        StoreOpexRuleRelDO storeOpexRuleRelDO = listOpex.get(0);
        Map ruleMap = new HashMap();
        ruleMap.put("ruleId", storeOpexRuleRelDO.getRuleId());
        ruleMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
        Map ruleRes = sysconfigFeign.getStoreOpexRule(ruleMap);
        if (ruleRes != null) {
            BigDecimal backCurrency = new BigDecimal(ruleRes.get("backCurrencyRatio").toString());
            BigDecimal discount = new BigDecimal(ruleRes.get("currencyPayDiscount").toString());
            discount = discount.divide(new BigDecimal(10));
            result.put("ratio", backCurrency);
            result.put("discount", discount);
            result.put("ruleId", storeOpexRuleRelDO.getRuleId());
            result.put("ruldeDes", storeOpexRuleRelDO.getRuleDes());
        }
        return R.ok(result);
    }
    @Override
    public R getCrossStoreByProviderId(Map<String, Object> params) {
        try {
            params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
            // 服务商id
            params.put("chainstoresuuid", FilterContextHandler.getName());
            params.put("auditstatus", StoreMainInfoEnum.BUSINESS_AUDIT_PASS);
            params.put("freezestatus", StoreMainInfoEnum.UNFROZEN);
            Query query = new Query(params);
            List<StoreMainInfoDO> list = list(query);
            int total = count(query);
            PageUtils pageUtil = new PageUtils(list, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }
    @Override
    public ApiResult getChildStoreView(Map<String, Object> mapParams) {
        // 解析map参数
        // 门店uuid
        Object temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return ApiResult.paramIsNull();
        }

        StoreShopDO shopModel = storeShopService.getByStoreUuid(storeUuid);
        StoreMainInfoDO mainInfoModel = get(storeUuid);
//        if (mainInfoModel != null) {
//            String fullName = storeCategoryService.getCategoryFullName(mainInfoModel.getServcategory(), "-");
//            mainInfoModel.setServCategoryName(fullName);
//        }
       /* if (shopModel != null) {
            String area = provinceService.getAreaName(shopModel.getProvince(), shopModel.getCity(), shopModel.getRegion(), "");
            shopModel.setArea(area);
            BusinessCircleModel businessCircleModel = businessCircleService.getByUuid(shopModel.getBusinessCircleUuid());
            if (businessCircleModel != null) {
                shopModel.setBusinessCircle(businessCircleModel.getBusinessCirName());
            }
        }*/

        Map result = new HashMap();
        result.put("shop", shopModel);
        result.put("mainInfo", mainInfoModel);

        return ApiResult.success(result);
    }
    @Override
    public R getYsUserInfo(Map<String, Object> params) {

        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return R.error("商户号为空");
        }
        StoreMainInfoDO storeMainInfo = get(storeUuid);
        Map returnResult = new HashMap();
        returnResult.put("ysUserCode", storeMainInfo.getYsusercode());
        returnResult.put("ysUserStatus", storeMainInfo.getYsuserstate());

        return R.data(returnResult);
    }

    @Override
    public ApiResult getWithdrawStoreList(Map<String, Object> params) {

        Object temp = params.get("storeName");
        String storeName = temp != null ? temp.toString() : null;

        Map queryMap = new HashMap();
        queryMap.put("storeName",storeName);

        List<StoreMainInfoDO> list =  storeMainInfoDao.getWithdrawStoreList(queryMap);
        List<WithdrawStoreDTO> withdrawStoreDTOList = new ArrayList<>(list.size());

        if(list.size()>0){
            for(StoreMainInfoDO store : list){
                withdrawStoreDTOList.add(WithdrawStoreConvert.MAPPER.DOToDTO(store));
            }
        }
        return ApiResult.success(withdrawStoreDTOList);
    }
}
